"""
景点序列化器
"""
from rest_framework import serializers
from .models import Attraction, AttractionReview, AttractionImage
from utils.number_formatter import format_price, format_rating, format_coordinate
from utils.amap_client import AMapClient
from django.conf import settings


class AttractionSerializer(serializers.ModelSerializer):
    """景点序列化器"""
    category_display = serializers.CharField(source='get_category_display', read_only=True)
    images_count = serializers.SerializerMethodField()
    reviews_count = serializers.SerializerMethodField()
    avg_rating = serializers.SerializerMethodField()
    ticket_price = serializers.SerializerMethodField()
    latitude = serializers.SerializerMethodField()
    longitude = serializers.SerializerMethodField()
    rating = serializers.SerializerMethodField()
    primary_image = serializers.SerializerMethodField()
    amap_images = serializers.SerializerMethodField()
    is_favorited = serializers.SerializerMethodField()
    favorites_count = serializers.SerializerMethodField()
    
    class Meta:
        model = Attraction
        fields = '__all__'
        read_only_fields = ('created_at', 'updated_at')
    
    def get_images_count(self, obj):
        """获取图片数量（优化：使用annotate避免N+1查询）"""
        if hasattr(obj, 'images_count_annotated'):
            return obj.images_count_annotated
        return obj.images.count()
    
    def get_reviews_count(self, obj):
        """获取评价数量（优化：使用annotate避免N+1查询）"""
        if hasattr(obj, 'reviews_count_annotated'):
            return obj.reviews_count_annotated
        return obj.reviews.count()
    
    def get_avg_rating(self, obj):
        from django.db.models import Avg
        avg = obj.reviews.aggregate(avg=Avg('rating'))['avg']
        return float(format_rating(avg)) if avg else 0.0
    
    def get_ticket_price(self, obj):
        """格式化门票价格，保留两位小数"""
        return float(format_price(obj.ticket_price))
    
    def get_latitude(self, obj):
        """格式化纬度，保留6位小数"""
        return float(format_coordinate(obj.latitude))
    
    def get_longitude(self, obj):
        """格式化经度，保留6位小数"""
        return float(format_coordinate(obj.longitude))
    
    def get_rating(self, obj):
        """格式化评分，保留两位小数"""
        return float(format_rating(obj.rating))
    
    def get_primary_image(self, obj):
        """获取主图URL（简化版，直接返回图片URL）"""
        try:
            # 直接返回第一张图片URL
            if obj.amap_image_urls and len(obj.amap_image_urls) > 0:
                url = obj.amap_image_urls[0]
                if url and isinstance(url, str) and url.startswith('http'):
                    return url
            return None
        except:
            return None
    
    def get_amap_images(self, obj):
        """获取高德地图图片URL列表（简化版）"""
        try:
            if obj.amap_image_urls and len(obj.amap_image_urls) > 0:
                # 只返回有效的HTTP URL
                return [url for url in obj.amap_image_urls if url and isinstance(url, str) and url.startswith('http')]
            return []
        except:
            return []
    
    def get_is_favorited(self, obj):
        """判断当前用户是否收藏了该景点（优化：避免N+1查询）"""
        # 如果已经通过prefetch_related预加载，直接使用
        if hasattr(obj, 'user_favorites'):
            return len(obj.user_favorites) > 0
        # 否则回退到原始查询（用于单个对象查询）
        request = self.context.get('request')
        if request and request.user.is_authenticated:
            return obj.favorited_by.filter(user=request.user).exists()
        return False
    
    def get_favorites_count(self, obj):
        """获取收藏数（优化：使用annotate避免N+1查询）"""
        # 如果已经通过annotate预加载，直接使用
        if hasattr(obj, 'favorites_count_annotated'):
            return obj.favorites_count_annotated
        # 否则回退到原始查询（用于单个对象查询）
        return obj.favorited_by.count()


class AttractionReviewSerializer(serializers.ModelSerializer):
    """景点评价序列化器"""
    user_username = serializers.CharField(source='user.username', read_only=True)
    
    class Meta:
        model = AttractionReview
        fields = ('id', 'user', 'user_username', 'rating', 'content', 'created_at', 'updated_at')
        read_only_fields = ('id', 'created_at', 'updated_at')


class AttractionImageSerializer(serializers.ModelSerializer):
    """景点图片序列化器"""
    image = serializers.SerializerMethodField()
    
    class Meta:
        model = AttractionImage
        fields = ('id', 'image', 'is_primary', 'created_at')
        read_only_fields = ('id', 'created_at')
    
    def get_image(self, obj):
        """获取图片URL（完整路径）"""
        try:
            if obj.image:
                request = self.context.get('request')
                if request:
                    # 使用build_absolute_uri构建完整URL
                    image_url = request.build_absolute_uri(obj.image.url)
                    return image_url
                # 如果没有request，返回相对路径
                return obj.image.url
            return None
        except Exception as e:
            # 如果出错，返回None而不是抛出异常
            import logging
            logger = logging.getLogger(__name__)
            logger.error(f'获取图片URL失败: {str(e)}')
            return None
